package com.zhentao.service.impl;


import com.zhentao.model.common.dtos.ApUser;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.common.wemedia.WmUser;
import com.zhentao.pojo.ApUserSearch;
import com.zhentao.pojo.dto.HistorySearchDto;
import com.zhentao.service.ApUserSearchService;
import com.zhentao.utils.user.AppThreadLocalUtil;
import com.zhentao.utils.wemedia.WmThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
* @author EWEWW
* @description 针对表【ap_user_search】的数据库操作Service实现
* @createDate 2024-06-25 18:46:56
*/
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService{
   @Autowired
   private MongoTemplate mongoTemplate;

    @Async //异步调用
    @Override
    public void insert(String keyword, Integer userId) {
        //1.查看当前用户搜索的关键词是否存在
       Query query = new Query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
       ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class,"ap_user_search");

       //2.如果存在 ， 更新一下创建时间
       if(apUserSearch != null){
           Update update = new Update().set("createdTime", new Date());
           mongoTemplate.updateFirst(query, update, ApUserSearch.class);
           return;
       }
       //3.如果不存在，判断当前历史记录的总数是否大于10
       ApUserSearch userSearch = new ApUserSearch();
       userSearch.setUserId(userId);
       userSearch.setKeyword(keyword);
       userSearch.setCreatedTime(new Date());

       Query query1 = new Query(Criteria.where("userId").is(userId));
       //根据时间降序
       query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
       List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);
       System.out.println(apUserSearchList.size()+"size");
       if(apUserSearchList == null || apUserSearchList.size()<10){
           //如果没有或者小于10条 ，新增
           mongoTemplate.save(userSearch);
       }else {//已经有10条了，把最后一条替换掉
           ApUserSearch lastSearch = apUserSearchList.get(apUserSearchList.size()-1);
           mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastSearch.getId())),userSearch);

       }
    }
    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch(String userId) {
        Query query = new Query(Criteria.where("userId").is("4"));
        //按照时间倒叙
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        for (ApUserSearch apUserSearch : apUserSearchList) {
            System.out.println("================>"+apUserSearch);
        }

        return ResponseResult.okResult(apUserSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.删除
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




